//
//  OCUserService.m
//  OCBase
//
//  Created by Duncan on 2021/1/12.
//

#import "OCUserService.h"
#import "WQLoginViewController.h"
#import <ThingSmartBizCore/ThingSmartBizCore.h>
#import <ThingSmartDeviceKit/ThingSmartHome+Weather.h>

@interface OCUserService () <ThingSmartHomeDelegate>

@end

@implementation OCUserService

+ (instancetype)share {
    static OCUserService *service = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        service = [DataStoreService getModelById:[self kj_runtimeClassName] className:[OCUserService class] fromTable:User] ?: [[self alloc] init];
    });
    return service;
}

- (instancetype)init {
    if (self = [super init]) {
        
        [[ThingSmartBizCore sharedInstance] registerService:@protocol(ThingSmartHomeDataProtocol) withInstance:self];
        [[ThingSmartBizCore sharedInstance] registerService:@protocol(ThingSmartHouseIndexProtocol) withInstance:self];
        
        // 登录会话过期
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionInvalid) name:ThingSmartUserNotificationUserSessionInvalid object:nil];
        
    }
    return self;
}


#pragma mark ------- Http Mehods -------

- (void)loginSuccessMethods {
    if (self.isLogin == NO) {
        return;
    }
    
    [self.homeManager getHomeListWithSuccess:^(NSArray<ThingSmartHomeModel *> *homes) {
        
        self.homes = homes;
        
        if (homes.count > 0) {
            ThingSmartHomeModel *homeModel = homes[0];
            
            // 获取当前选择家庭的信息
            self.userHomeModel = [ThingSmartHome homeWithHomeId:homeModel.homeId];
            self.userHomeModel.delegate = self;
            [self updateHomeDetail];
            [self getHomeWeatherDetail];
        }
        
    } failure:^(NSError *error) {
        DEBUGLOG(@"获取家庭列表失败");
    }];
}

/// 添加设备
- (void)addDeviceMethods {
    if (!self.isLoginUserAndPresent) {
        return;
    }
    id<ThingActivatorProtocol> impl = [[ThingSmartBizCore sharedInstance] serviceOfProtocol:@protocol(ThingActivatorProtocol)];
    [impl gotoCategoryViewController];
    
    [impl activatorCompletion:ThingActivatorCompletionNodeNormal customJump:NO completionBlock:^(NSArray * _Nullable deviceList) {
        
        DEBUGLOG(@"获取配网结果 activatorCompletiondeviceList: %@",deviceList);
    }];
}

/// 打开配网扫一扫
- (void)openScanMainMethods {
    if (!self.isLoginUserAndPresent) {
        return;
    }
    
    id<ThingActivatorProtocol> impl = [[ThingSmartBizCore sharedInstance] serviceOfProtocol:@protocol(ThingActivatorProtocol)];
    [impl gotoQRCodeViewControllerWithUserInfo:nil];
    
    [impl activatorCompletion:ThingActivatorCompletionNodeNormal customJump:NO completionBlock:^(NSArray * _Nullable deviceList) {
        
        DEBUGLOG(@"获取配网结果 activatorCompletiondeviceList: %@",deviceList);
    }];
}

/// 创建场景
- (void)addSceneMainMethods {
    if (!self.isLoginUserAndPresent) {
        return;
    }
    
    id<ThingSmartSceneProtocol> impl = [[ThingSmartBizCore sharedInstance] serviceOfProtocol:@protocol(ThingSmartSceneProtocol)];
    [impl addAutoScene:^(ThingSmartSceneModel *secneModel, BOOL addSuccess) {
        if (addSuccess) {
            DEBUGLOG(@"创建场景成功");
        } else {
            DEBUGLOG(@"创建场景失败");
        }
    }];
}

#pragma mark ------- 家庭 -------

- (ThingSmartHome *)getCurrentHome {
    return self.userHomeModel;
}
- (BOOL)homeAdminValidation {
    return YES;
}

//- (long long)currentFamilyId {
//    return self.home.homeModel.homeId;
//}

// 更新家庭数据
- (void)updateHomeDetail {
    if (self.isLogin == NO) {
        return;
    }
    
    [self.userHomeModel getHomeDataWithSuccess:^(ThingSmartHomeModel *homeModel) {

        DEBUGLOG(@"获取家庭数据成功");
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationFamilyUpdate object:nil];
        
    } failure:^(NSError *error) {
        
        DEBUGLOG(@"获取家庭数据失败");
        
    }];
}

/// 弹出切换家庭view
- (void)showExchangeFramilyListView {
    if (self.isLogin == NO) {
        return;
    }
    
    NSArray *nameArray = [self.homes kj_mapArray:^NSString * _Nonnull(ThingSmartHomeModel *  _Nonnull object) {
        return object.name;
    }];
    
    kWEAKSELF
    [TSHandleAlertView pad_showSystemSheetViewWithTitleArray:nameArray confirm:^(NSInteger buttonTag) {
        
        ThingSmartHomeModel *homeModel = weakSelf.homes[buttonTag];
        
        // 获取当前选择家庭的信息
        weakSelf.userHomeModel = [ThingSmartHome homeWithHomeId:homeModel.homeId];
        weakSelf.userHomeModel.delegate = self;
        [weakSelf updateHomeDetail];
        [weakSelf getHomeWeatherDetail];
        
    } view:[UIApplication currentRootTopViewController].view frame:CGRectZero];
}

- (void)homeDidUpdateInfo:(ThingSmartHome *)home {
    DEBUGLOG(@"家庭信息更改通知");
}

-(void)home:(ThingSmartHome *)home didAddDeivice:(ThingSmartDeviceModel *)device {
    DEBUGLOG(@"家庭信息更改通知");
}

-(void)home:(ThingSmartHome *)home didRemoveDeivice:(NSString *)devId {
    DEBUGLOG(@"家庭信息更改通知");
}

-(void)home:(ThingSmartHome *)home deviceInfoUpdate:(ThingSmartDeviceModel *)device {
    DEBUGLOG(@"家庭信息更改通知");
}

-(void)home:(ThingSmartHome *)home device:(ThingSmartDeviceModel *)device dpsUpdate:(NSDictionary *)dps {
    DEBUGLOG(@"家庭信息更改通知");
}

// 查询家庭天气详细参数
- (void)getHomeWeatherDetail {
    [self.userHomeModel getHomeWeatherDetailWithOption:nil success:^(NSArray<ThingSmartWeatherModel *> *weatherModels) {
        
        DEBUGLOG(@"success get weather model: %@", weatherModels);
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationFamilyWeatherReload object:nil];
        
    } failure:^(NSError *error) {
        DEBUGLOG(@"failure with error: %@", error);
    }];
}


#pragma mark ------- Notification Methods -------

- (void)sessionInvalid {
    DEBUGLOG(@"登录会话过期");
    
    [self logutOutOrTokenOverdue];
}

#pragma mark ------- Public Methods -------

- (void)save {
    [DataStoreService putModel:self withId:[self kj_runtimeClassName] intoTable:User];
}

// 保存并发通知
- (void)saveAndPostNotification {
    [self save];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationUserInfoUpdate object:nil];
}

/// 退出登录，token过期等
- (void)logutOutOrTokenOverdue {
    
    [[ThingSmartUser sharedInstance] loginOut:^{
        DEBUGLOG(@"logOut success");
    } failure:^(NSError *error) {
        DEBUGLOG(@"logOut failure: %@", error);
    }];

    [DataStoreService clearTable:User];
    self.isVisitorsLogin = NO;
    
    self.homes = nil;
    self.userHomeModel = nil;

    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationUserInfoUpdate object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationLogutOutOrTokenOverdue object:nil];
}

/// 获取用户token
+ (NSString *)getUserToken {
    NSString *token = [DataStoreService getStringById:kDataStoreToken fromTable:User];
    return token ?: @"";
}
+ (NSString *)getUserID {
//    return WQShare.userInfoModel.ID ?: @"";
    return @"";
}

/// 判断是否登录
- (BOOL)isLogin {
    return [ThingSmartUser sharedInstance].isLogin;
}

/// 判断是否登录并且跳出登录界面
- (BOOL)isLoginUserAndPresent {
    
    if (self.isLogin == YES) {
        return YES;
        
    } else {
        WQLoginViewController *vc = [[WQLoginViewController alloc] init];
        [[UIApplication currentViewController].navigationController pushViewController:vc animated:YES];
        return NO;
    }
}


- (ThingSmartHomeManager *)homeManager {
    if (!_homeManager) {
        _homeManager = [[ThingSmartHomeManager alloc] init];
    }
    return _homeManager;
}

@end
